#include "configmanager.h"
#include <QApplication>
#include <QDir>
#include "systemconfig.h"
#include <QMutexLocker>
#include <QDebug>

SINGLETON_IMPLIMENT(ConfigManager)

ConfigManager::ConfigManager(QObject *parent)
    : QObject (parent)
{
    qDebug() << "ConfigManager...";
    m_configMap.clear();

    directory = QApplication::applicationDirPath() + "/ini/";
    QDir dir(directory);
    if (!dir.exists())
        dir.mkdir(directory);

//    QString path = directory + QApplication::applicationName() + ".ini";
    QString path = directory + "system.ini";
    m_systemConfig = new SystemConfig(path, parent);
    if (!m_systemConfig->init())
    {
        qCritical() << "Error : no data";
        return;
    }

    loadAll();
    qDebug() << "ConfigManager...completed";
}

ConfigManager::~ConfigManager()
{

}

bool ConfigManager::get(ConfigKey key, QVariant &value)
{
    QMutexLocker locker(&m_mapMutex);

    if (m_configMap.contains(key))
    {
        value = m_configMap.value(key);
        return true;
    }
    return false;
}

bool ConfigManager::set(ConfigKey key, const QVariant &value)
{
    QMutexLocker locker(&m_mapMutex);

    if (m_configMap.contains(key))
    {
        // 更新内存
        m_configMap.insert(key, value);

        // 直接写
        m_systemConfig->set(key, value);

        return true;
    }
    return false;
}

QVariant ConfigManager::get(ConfigKey key)
{
    QMutexLocker locker(&m_mapMutex);

    if (m_configMap.contains(key))
    {
        return m_configMap.value(key);
    }
    return QVariant();
}

void ConfigManager::onStart()
{
    QMutexLocker locker(&m_mapMutex);
    qDebug() << "ConfigManager onStart...";
//    loadAll();

    // 可以在线程启动后做一些其他的加载动作等
}

void ConfigManager::loadAll()
{
    // 加载全部系统数据
    qDebug() << "load all data...";
    QList<ConfigKey> keys = m_systemConfig->allKeys();
    foreach (auto it, keys)
    {
        QVariant var;
        m_systemConfig->get(it, var);
        m_configMap.insert(it, var);
    }
    qDebug() << "load all data...completed";
}

